use crate::AppWindow;
use anyhow::Error;
use slint::ComponentHandle;
use tokio::sync::mpsc::{unbounded_channel, UnboundedSender};
use tokio::task::JoinHandle;

pub enum Message {
    Quit,
}

pub struct Worker {
    pub channel: UnboundedSender<Message>,
    worker_thread: JoinHandle<()>,
}

impl Worker {
    pub fn new(ui: &AppWindow) -> Self {
        let (tx, mut rx) = unbounded_channel::<Message>();
        let ui_handle = ui.as_weak();

        let worker_thread = tokio::spawn(async move {
            while let Some(message) = rx.recv().await {
                match message {
                    Message::Quit => {
                        break;
                    }
                }
            }
        });

        Self {
            channel: tx,
            worker_thread: worker_thread,
        }
    }

    pub async fn join(self) -> Result<(), Error> {
        let _ = self.channel.send(Message::Quit);
        self.worker_thread.await?;
        Ok(())
    }
}
